//
//  LoadWebTools.swift
//  sdxf
//
//  Created by 湛亚磊 on 2020/1/17.
//  Copyright © 2020 湛亚磊. All rights reserved.
//

import UIKit
import WebKit

open class LoadWebTools: NSObject,WKNavigationDelegate,UIScrollViewDelegate {

    private var wkWebConfig:WKWebViewConfiguration{
        let wkWebConfig = WKWebViewConfiguration()
        wkWebConfig.preferences.javaScriptEnabled = true
        ///禁止长按
        let jScriptLongClick : String="document.documentElement.style.webkitTouchCallout='none';"
        let wkUScriptLongClick = WKUserScript(source: jScriptLongClick, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        ///z禁止选择
        let jScriptChoise : String="document.documentElement.style.webkitUserSelect='none';"
        let wkUScriptChoise = WKUserScript(source: jScriptChoise, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        ///文字图片自适应
        let jScriptScal : String="var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].style.maxWidth='100%';imgs[i].style.height='auto';}"
        let wkUScriptScal = WKUserScript(source: jScriptScal, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        
        
        let wkUController=WKUserContentController()
        wkUController.addUserScript(wkUScriptScal)
        wkUController.addUserScript(wkUScriptLongClick)
        wkUController.addUserScript(wkUScriptChoise)
        
        wkWebConfig.userContentController = wkUController
        return wkWebConfig
    }
    
    
    private var webViewISScal=true
    
    public var outBlock:((WKWebView,CGFloat)->())?
    
    public var loadContent:String = ""{
        didSet{
            if loadContent != ""{
                ToastView.instance.showLoadingView()
                webViewM.loadHTMLString(loadContent, baseURL: nil)
            }
        }
    }
    
    var initWebViewFrame:CGRect = CGRect.zero
    
    
    public var loadURL:String = ""{
        didSet{
            if loadURL != ""{
                ToastView.instance.clear()
                if let tempUrl=URL(string: loadURL){
                    webViewM.load(URLRequest(url: tempUrl, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 3000))
                }else{
                }
            }
        }
    }
    
    ///webview
    private lazy var webViewM: WKWebView = {
        let webViewM=WKWebView(frame: initWebViewFrame, configuration: wkWebConfig)
        webViewM.scrollView.isScrollEnabled=false
        webViewM.navigationDelegate = self
        webViewM.scrollView.delegate = self
        webViewM.scrollView.isUserInteractionEnabled=true
        return webViewM
    }()
    
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webViewISScal=false
        // 获取内容实际高度
    }
    
    public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        if webViewISScal {
            return nil
        }else{
            return webViewM.scrollView.subviews[0]
        }
    }
    
    public override init() {
        super.init()
        self.webViewM.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
    }
    
    
    deinit {
        self.webViewM.removeObserver(self, forKeyPath: "estimatedProgress")
        self.webViewM.uiDelegate = nil
        self.webViewM.navigationDelegate = nil
    }
    
    
    public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //  加载进度条
        if keyPath == "estimatedProgress"{
            if (self.webViewM.estimatedProgress)  >= 1.0 {
                ToastView.instance.clear()
                self.webViewM.evaluateJavaScript("document.body.scrollHeight") { [weak self] (result, error) in
                    if let tempHeight: Double = result as? Double {
                        self?.outBlock?(self!.webViewM,CGFloat(tempHeight))
                    }
                }
            }
        }
    }
}
